package main

import (
	"github.com/gin-gonic/gin"
	"qwork.site/shortme/config"
	"qwork.site/shortme/models"
	"log"
	"net/http"
)

var (
	defaultUrl string
	port       string
	except     = "favicon.ico"
	err        error
)
type RequestData struct {
	LongUrl string `form:"long_url" json:"long_url"`
	Hash  string    `form:"hash" json:"hash"`
}

func init() {
	defaultUrl, err = config.GetByBlock("common", "defaulturl")
	port, err = config.GetByBlock("common", "appport")
	if err != nil {
		log.Printf("func config.Get got err : %+v", err)
	}
}

func main() {
	r := gin.Default()

	r.LoadHTMLGlob("template/*")
	r.StaticFS("/static", http.Dir("./static"))
	
	r.GET("/go:hash", expandUrl)

	r.GET("/", func(c *gin.Context) {
		c.HTML(200, "index.html", gin.H{})
	})
	r.POST("/", shorten)
	r.GET("/lookup/:hash", lookup)

	r.Run(port)
}

func expandUrl(c *gin.Context) {
	hash := c.Param("hash")
	if hash == except {
		return
	}
	url := models.FindLongUrl(hash)
	if url != "" {
		c.Redirect(http.StatusFound, url)
		return
	} else {
		c.HTML(200, "e404.html", gin.H{})
	}
}

func shorten(c *gin.Context) {
	var data RequestData
	ct := c.GetHeader("Content-Type")

	if ct == "application/json" {
		c.BindJSON(&data)
	} else {
		c.Bind(&data)
	}

	url, err := models.Save(data.LongUrl, data.Hash)
	if err != nil {
		panic(err)
	}
	
	if ct == "application/json" {
		c.JSON(200, gin.H{
			"action": "shorten",
			"result": defaultUrl + url.HASH,
		})
	} else {
		c.HTML(200, "result.html", gin.H{
			"ok":     true,
			"result": defaultUrl + url.HASH,
		})
	}
}

func lookup(c *gin.Context) {
	hash := c.Param("hash")
	ct := c.GetHeader("Content-Type")
	url := models.Find(hash)
	if ct == "application/json" {
		c.JSON(200, gin.H{
			"action": "lookup",
			"result": url,
		})
	} else {
		c.HTML(200, "result.html", gin.H{
			"ok":     true,
			"result": defaultUrl + url.HASH,
		})
	}
}
